/*
 * @Descripttion: url处理工具类
 * @version:
 * @Author: gonghong
 * @Date: 2021-10-25 11:44:28
 */

/**
 * @function 把参数对象里的属性拼接到url上get传参
 * @param baseUrl
 * @param obj
 * @returns
 */
export const setObjToUrlParams = (baseUrl: string, obj: object): string => {
    let url: string = ''
    let parameters: string = ''
    for (const key in obj) {
        parameters += key + '=' + encodeURIComponent(obj[key]) + '&'
    }
    parameters = parameters.replace(/&$/, '')
    if (/\?$/.test(baseUrl)) {
        url = baseUrl + parameters
    } else {
        url = baseUrl.replace(/\/?$/, '?') + parameters
    }
    return url
}

/**
 * @function 把url的参数转化为对象进行获取
 * @param baseUrl
 * @param key
 * @returns
 */
export const getUrlParamsToObj = (baseUrl?: string, key?: string): object | undefined => {
    const url: string = baseUrl || window.location.search || ''
    const urlArr: Array<string> = url.split('?')
    if (urlArr[1] && urlArr[1].length > 0) {
        const paramsArr = urlArr[1].split('&')
        let params:{} = {}
        paramsArr.map((str) => {
            let strArr = str.split('=')
            if (strArr[0]) {
                params[strArr[0]] = strArr[1]
            }
        })
        if (key) {
            if (params[key]) {
                return params[key]
            } else {
                return undefined
            }
        } else {
            return params
        }
    } else {
        return undefined
    }
}
